package com.jeff.jcryptor;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.jeff.cryptor.lib.Cryptor;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    EditText et_content;
    Button bt_check_sign;
    Button bt_encode;
    Button bt_decode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt_check_sign = findViewById(R.id.bt_check_sign);
        et_content = findViewById(R.id.et_content);
        bt_encode = findViewById(R.id.bt_encode);
        bt_decode = findViewById(R.id.bt_decode);
        bt_check_sign.setOnClickListener(this);
        bt_encode.setOnClickListener(this);
        bt_decode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_check_sign:
                verify();
                break;

            case R.id.bt_encode:
                encode();
                break;

            case R.id.bt_decode:
                decode();
                break;
        }
    }

    private void verify() {
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
            Signature[] signatures = pInfo.signatures;
            Signature sign = signatures[0];
            if (sign != null) {
                Log.d("jeff", "Sign hashcode:" + sign.hashCode());
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Toast.makeText(MainActivity.this,
                Cryptor.verify(MainActivity.this) ? "Verify success!" : "Verify fail!",
                Toast.LENGTH_SHORT).show();
    }

    private void encode() {
        String content = et_content.getText().toString();
        if (!TextUtils.isEmpty(content)) {
            String result = Cryptor.encrypt(this, content);
            et_content.setText(result);
            Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
        }
    }

    private void decode() {
        String content = et_content.getText().toString();
        if (!TextUtils.isEmpty(content)) {
            String result = Cryptor.decrypt(this, content);
            et_content.setText(result);
            Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
        }
    }

}

